package com.hust.chatvedio.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.view.menu.MenuBuilder;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.hust.chatvedio.*;
import com.hust.chatvedio.Entity.FriendEntity;
import com.hust.chatvedio.adapter.FriendViewAdapter;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ChatFragment extends Fragment implements AdapterView.OnItemClickListener {

    private Toolbar mToolbar;
    private ProgressDialog progressDialog;
    //发送信息地址
    private static String url_getChatList = MainActivity.BaseURL + "getChatList";
    private FriendViewAdapter friendViewAdapter;
    private ListView mListView1;
    private List<FriendEntity> mDataArrays = new ArrayList<FriendEntity>();
    private int success;//服务器返回值
    private String friend_name;//服务器返回值
    private String friend_avatar;//服务器返回值
    private String group_name;//服务器返回值
    private String group_avatar;//服务器返回值
    public static int chatListsLength;//聊天窗口数目



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chat, container, false);
        initView(view);
        initData();
        setHasOptionsMenu(true);
        return view;
    }

    private void initView(View view) {
        mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        mToolbar.setOverflowIcon(getResources().getDrawable(R.drawable.add));
        MenuActivity menuActivity = (MenuActivity) getActivity();
        menuActivity.setSupportActionBar(mToolbar);
        mListView1 = (ListView)view.findViewById(R.id.listView);
        mListView1.setOnItemClickListener(this);
    }

    private void initData() {
        friendViewAdapter = new FriendViewAdapter(mDataArrays, getActivity());
        mListView1.setAdapter(friendViewAdapter);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.main, menu);
        if (menu != null) {
            if (menu.getClass() == MenuBuilder.class) {
                try {
                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                }
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search_item:
                Toast.makeText(getContext(), "开发中，耐心等待哦~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.chat_item:
                Intent intentLuanchChat = new Intent(getActivity(), LuanchChatActivity.class);
                startActivity(intentLuanchChat);
                break;
            case R.id.addfriend_item:
                Intent intentAddFriend = new Intent(getActivity(), AddFriendActivity.class);
                startActivity(intentAddFriend);
                break;
            case R.id.addGroup_item:
                Intent intentAddGroup = new Intent(getActivity(), AddGroupActivity.class);
                startActivity(intentAddGroup);
                break;
            case R.id.pay_item:
                Toast.makeText(getContext(), "开发中，耐心等待哦~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.help_item:
                Toast.makeText(getContext(), "开发中，耐心等待哦~", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }//check_item
        return super.onOptionsItemSelected(item);
    }


    public void getChatList() {
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        Map<String, String> map = new HashMap<>();
        map.put("userName", MainActivity.userName);
        //在进行异步任务前先显示一个 Progress Dialog
        progressDialog=new ProgressDialog(getActivity());
        progressDialog.setMessage("获取消息列表");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(true);
        progressDialog.show();
        Request request = new JsonObjectRequest(1, url_getChatList, new Gson().toJson(map),
                jsonObject -> {
                    try {
                        success = jsonObject.getInt("success");
                        if (success == 1) {
                            mDataArrays.clear();
                            progressDialog.dismiss();
                            JSONArray data = jsonObject.getJSONArray("data");
                            chatListsLength = data.length();
                            mToolbar.setTitle("ChatVedio("+String.valueOf(chatListsLength)+")");
                            MenuActivity.mAlphaIndicator.getTabView(0).showNumber(chatListsLength);
                            for(int i=0;i<data.length();i++) {
                                FriendEntity entity = new FriendEntity();
                                entity.setName(data.getJSONObject(i).optString("name"));
                                entity.setAvatarUrl(data.getJSONObject(i).optString("avatar"));
                                entity.setNewMsg(data.getJSONObject(i).optString("newMsg"));
                                //本地显示
                                mDataArrays.add(entity);
                            }
                                friendViewAdapter.notifyDataSetChanged();
//                                    mListView1.setSelection(mListView1.getCount() - 1);
                        } else if (success == 0) {
                            progressDialog.dismiss();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }, volleyError -> {
                });
        requestQueue.add(request);
    }



    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(getActivity(), "点击了"+position, Toast.LENGTH_SHORT).show();
        String chatName = mDataArrays.get(position).getName();
        Intent intent = new Intent(getActivity(),ChatActivity.class);
        intent.putExtra("chatName",chatName);
        startActivity(intent);
    }



    @Override
    public void onResume() {
        super.onResume();
        getChatList();
    }


}